package com.han.agent.interview;

import lombok.RequiredArgsConstructor;
import org.springframework.ai.document.Document;
import org.springframework.ai.reader.TextReader;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class InterviewService {

    @Value("classpath:Java基础面试题.md")
    private String resource;

    private final VectorStore vectorStore;

    public List<Document> loadText() {
        TextReader textReader = new TextReader(resource);
        List<Document> documents = textReader.get();

        MarkdownSplitter textSplitter = new MarkdownSplitter();
        List<Document> list = textSplitter.apply(documents);

        List<Document> list1 = list.stream().map(d -> {
            String[] split = d.getText().split("==title==");
            Map<String, Object> metadata = d.getMetadata();
            metadata.put("question", split[0].replace("##", ""));
            return Document.builder()
                    .text(split[1].trim())
                    .id(d.getId())
                    .score(d.getScore())
                    .metadata(metadata)
                    .media(d.getMedia())
                    .build();
        }).toList();

        vectorStore.add(list1);
        return list;
    }

    public List<Document> search(String question) {
        // 先查元数据
        SearchRequest metaSearchRequest = SearchRequest.builder()
                .query(question)
                .topK(3)
                .similarityThreshold(0.9)
                .filterExpression(String.format("question in ['%s']", question))
                .build();

        List<Document> metaDocuments = vectorStore.similaritySearch(metaSearchRequest);
        if (!CollectionUtils.isEmpty(metaDocuments)) {
            return metaDocuments;
        }

        // 元数据没查到在相似搜索
        SearchRequest searchRequest = SearchRequest.builder()
                .query(question)
                .topK(3)
                .similarityThreshold(0.9).build();

        return vectorStore.similaritySearch(searchRequest);

    }
}
